﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace AMing.Mvc4.Data.LocaData
{
    public class PageHtmlData : BaseGetData
    {
        public PageHtmlData(HttpServerUtilityBase server)
            : base(server)
        {
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Model.AjaxPage.AjaxHtml GetData(string key)
        {
            try
            {
                Dictionary<string, Model.AjaxPage.AjaxHtml> dicData = null;
                string filepath = base.Server.MapPath(Config.PageHtmlDataFilePath);
                string jsondata = Core.Method.TextFile.TxtFileRead(filepath);
                if (jsondata != null)
                {
                    dicData = Core.Helper.JsonHelper.Deserialize<Dictionary<string, Model.AjaxPage.AjaxHtml>>(jsondata, null);
                    if (dicData != null)
                    {
                        if (dicData.ContainsKey(key))
                        {
                            return dicData[key];
                        }
                    }
                }

                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="ajaxHtml"></param>
        /// <returns></returns>
        public bool WriteData(string key, Model.AjaxPage.AjaxHtml ajaxHtml)
        {
            try
            {
                Dictionary<string, Model.AjaxPage.AjaxHtml> dicData = new Dictionary<string, Model.AjaxPage.AjaxHtml>();
                string filepath = base.Server.MapPath(Config.PageHtmlDataFilePath);
                string jsondata = Core.Method.TextFile.TxtFileRead(filepath);
                if (jsondata != null)
                {
                    Dictionary<string, Model.AjaxPage.AjaxHtml> tempdata = Core.Helper.JsonHelper.Deserialize<Dictionary<string, Model.AjaxPage.AjaxHtml>>(jsondata, null);
                    if (tempdata != null)
                    {
                        dicData = tempdata;
                    }
                }
                dicData.Add(key, ajaxHtml);
                jsondata = Core.Helper.JsonHelper.Serialize(dicData);
                Core.Method.TextFile.TxtFileWrite(filepath, jsondata);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
